from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, mixins
from rest_framework import viewsets
from goods.models import GoodsGroup, GoodsBanner, Goods, Collect, Detail
from goods.serializers import GoodsSerializer, GoodsGroupSerializer, GoodsBannerSerializer, CollectSerializer, DetailSerializer
from rest_framework.permissions import IsAuthenticated

from goods.permissions import CollectPermissions

"""
商品模块前端接口

1，商城首页：
    商品的分类信息
    商品的海报图
    商品【推荐】的列表【分页
    
2，点击某个商品：
    商品详情信息

3，分类获取商品
    未上架商品不获取
    支持分类获取【过滤参数
    支持推荐商品
    支持排序【销量，价格，库存
    
4，收藏商品【取消
"""


# Create your views here.


class IndexView(APIView):

    def get(self, request):
        """ 商城首页接口 """
        # 获取商品所有的分类信息
        group = GoodsGroup.objects.filter(status=True)
        # context={'request': request}
        # 序列化如果有图片字段，需要添加 来补全返回数据的url的域名
        group_ser = GoodsGroupSerializer(instance=group, many=True, context={'request': request})  # 序列化返回数据

        # 获取商品的海报图
        banner = GoodsBanner.objects.filter(status=True)
        banner_ser = GoodsBannerSerializer(instance=banner, many=True, context={'request': request})  # 序列化返回数据

        # 获取所有的推荐商品
        goods = Goods.objects.filter(recommend=True)
        goods_ser = GoodsSerializer(instance=goods, many=True, context={'request': request})  # 序列化返回数据

        result = {
            'group': group_ser.data,
            'banner': banner_ser.data,
            'goods': goods_ser.data,
        }
        return Response(result, status=status.HTTP_200_OK)


class GoodsView(viewsets.ReadOnlyModelViewSet):
    """
    商品是图集
        商品列表接口
        get：获取单个或所有商品
    """
    # 查询集 只获取上架的商品
    queryset = Goods.objects.filter(is_on=True)
    serializer_class = GoodsSerializer

    # 实现通过商品的分类，和是否推荐过滤
    filterset_fields = ('group', 'recommend')

    # 支持排序【销量，价格，库存
    ordering_fields = ('id', 'sales', 'price', 'stock')

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)

        # 获取商品详情
        # 判断该商品是否有详情信息
        if not Detail.objects.filter(goods=instance).exists():
            result = serializer.data
            result['detail'] = {}  # 没有就为空
            return Response(result)
        else:
            detail = Detail.objects.get(goods=instance)
            # 序列化数据
            detail_ser = DetailSerializer(instance=detail)
            # 返回结果
            result = serializer.data
            result['detail'] = detail_ser.data
            return Response(result)


class CollectView(GenericViewSet,
                  mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  mixins.DestroyModelMixin):
    """
    商品收藏视图集

        destroy: 取消收藏，
        list: 收藏列表
    """
    queryset = Collect.objects.all()
    serializer_class = CollectSerializer

    # 权限设置【登录用户才能操作
    # 设置认证用户才能访问
    permission_classes = [IsAuthenticated, CollectPermissions]

    def create(self, request, *args, **kwargs):
        """ create: 收藏商品 """
        # 获取请求参数
        user = request.user  # 当前用户
        params_user_id = request.data.get('user')  # 要收藏的用户id
        print(type(user.id), type(params_user_id))
        print(user.id, params_user_id)
        print(user.id != params_user_id)
        # 校验请求参数中的用户id是否为当前登录的用户id
        if int(user.id) != int(params_user_id):
            return Response({'error': '没有操作其他用户的权限'})

        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        # 获取列表
        queryset = self.filter_queryset(self.get_queryset())
        # 过滤列表【登录用户的
        queryset = queryset.filter(user=request.user)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class GoodsGroupView(GenericViewSet,
                     mixins.ListModelMixin):
    """ 商品分类视图集 """
    queryset = GoodsGroup.objects.filter(status=True)
    serializer_class = GoodsGroupSerializer

# class GoodsGroupView(APIView):
#     def get(self, request):
#         group = GoodsGroup.objects.filter(status=True)
#         # context={'request': request}
#         # 序列化如果有图片字段，需要添加 来补全返回数据的url的域名
#         group_ser = GoodsGroupSerializer(instance=group, many=True, context={'request': request})  # 序列化返回数据
#
#         return Response(group_ser.data, status=status.HTTP_200_OK)
